<?php  

/* Return last run date, 
 * $daemon_key would be unique identifier
*/
require_once(DAEMONE_HOME.'/lib/lib_database.php');

function get_last_run_date($daemon_key) 
{
	$sql = "select * from daemon_meta where daemon_key='$daemon_key'";
	$result = execute_query($sql);
	
	if($result === FALSE) 
	{
		throw new Exception("sql:$sql ".mysql_error());
	}
	
	if (mysql_num_rows($result) == 0) 
	{
		$sql = "insert into daemon_meta (daemon_key, last_run_datetime) values ('$daemon_key', now())";
		$result = execute_query($sql);
		return date('Y-m-d H:i:s');
		throw new Exception('daemon meta not found for daemon_key='.$daemon_key);
	}
	
	$row = mysql_fetch_assoc($result);
	
	return $row['last_run_datetime'];
}


function update_last_run_datetime($daemon_key, $datetime) 
{
	$sql = "update daemon_meta set last_run_datetime='$datetime' where daemon_key='$daemon_key'";
	$result = execute_query($sql);
	
	if($result === FALSE) 
	{
		throw new Exception("sql:$sql ".mysql_error());
	}
	echo "debug::{status:'success', sql:'$sql'}", "\r\n";
}

function run_query_with_logging($sql,$script)
{
	$status = '';
	$message = '';
	
	$result = execute_query($sql);

	if($result === FALSE) 
	{
		echo "debug::{status:'fail', script:'$script', sql:'$sql', message:'",mysql_error(),"' }", "\r\n";
		throw new Exception("sql:$sql ".mysql_error());
	}
	else 
	{
		echo "debug::{status:'success', script:'$script', sql:'$sql', message:'success' }", "\r\n";
		return $result;
	}
}

function parseNprocessItem(&$item, $item_lookup_id = NULL)
{
	global $category_id, $category_name;
	try 
	{	
		// echo json_encode($item),"\r\n";
		$uid = $item->ASIN;
		$product_url = $item->DetailPageURL;
		$orignalPrice = $item->ItemAttributes->ListPrice->Amount; 
		if(property_exists($item->Offers, 'Offer'))
		{
			if(is_array($item->Offers->Offer))
			{
				$offer = $item->Offers->Offer[0]; 
			}
			else 
			{
				$offer = $item->Offers->Offer; 
			}

			$salePrice = $offer->OfferListing->Price->Amount;
		}
		else
		{
			$salePrice = $item->ItemAttributes->ListPrice->Amount; 
		}
		

		$orignalPrice = $orignalPrice / 100; 
		$salePrice = $salePrice / 100;
		// print_r($item); exit;
		
		// Editorial Review
		if(property_exists($item,'EditorialReviews'))
		{
			if(property_exists($item->EditorialReviews,'EditorialReview')) 
			{
				if (is_array($item->EditorialReviews->EditorialReview))
				{
					$editorialReview = $item->EditorialReviews->EditorialReview[0];
				}
				else 
				{
					$editorialReview = $item->EditorialReviews->EditorialReview;
				}
			}
		}
		
		$description = '';
		if (isset($editorialReview) && property_exists($editorialReview, 'Content'))
			$description = addslashes($editorialReview->Content); 
		
		$title = addslashes(trim($item->ItemAttributes->Title));
		if(empty($title))
			return;

		$manufacturer = '';
		if(property_exists($item,'ItemAttributes') && property_exists($item->ItemAttributes,'Manufacturer'))
			$manufacturer = addslashes($item->ItemAttributes->Manufacturer); 	
		
		$smallImageUrl = '';
		$mediumImageUrl = '';
		$largeImageUrl = '';
		if(property_exists($item, 'ImageSets') && property_exists($item->ImageSets, 'ImageSet'))
		{
			if(is_array($item->ImageSets->ImageSet))
			{
				$imageSet = $item->ImageSets->ImageSet[0];
			}
			else 
			{
				$imageSet = $item->ImageSets->ImageSet;
			}
			$smallImageUrl = $imageSet->SmallImage->URL;
			$mediumImageUrl = $imageSet->MediumImage->URL;
			$largeImageUrl = $imageSet->LargeImage->URL;
		}
		
		$image_name = '';
		$image_dir_path = '';
		// Customer Review
		$customerReviewLink = '';
		if(property_exists($item,'CustomerReviews'))
		{
			if(property_exists($item->CustomerReviews,'HasReviews') && $item->CustomerReviews->HasReviews == 1) 
			{
				$customerReviewLink = $item->CustomerReviews->IFrameURL;
				
			}
		}
		
		$sql = "INSERT IGNORE INTO products ( 
				  slug_product_title
				, product_title
				, meta_keywords
				, meta_desc
				, product_desc
				, original_price
				, sale_price
				, image_name
				, image_dir_path
				, is_hot_product
				, post_date
				, category_id
				, rss_publish_date
				, post_modified
				, aff_img_small
				, aff_img_medium
				, aff_img_large
				, aff_uid
				, aff_url
				, customer_review_link
			) VALUES ( '"
			.	 strtolower(preg_replace('/[-]+/', '-', preg_replace('/[\W]/', '-', $title )))
			. "'
				,'$title'
				,'$title, $manufacturer, $category_name'
				,'$description'
				,'$description'
				,'$orignalPrice'
				,'$salePrice'
				,'$image_name'
				,'$image_dir_path'
				, 0
				, now()
				, $category_id
				, now()
				, now()
				,'$smallImageUrl'
				,'$mediumImageUrl'
				,'$largeImageUrl'
				,'$uid'
				,'$product_url'
				,'$customerReviewLink'
			)
			ON DUPLICATE KEY UPDATE 
				  product_title = '$title'
				, meta_keywords = '$title, $manufacturer, $category_name'
				, meta_desc = '$description'
				, product_desc = '$description'
				, original_price = '$orignalPrice'
				, sale_price = '$salePrice'
				, aff_img_small = '$smallImageUrl'
				, aff_img_medium = '$mediumImageUrl'
				, aff_img_large = '$largeImageUrl'
				, customer_review_link = '$customerReviewLink'
			";
		// echo $sql, "\r\n<br/>";
		$result = execute_insert_query($sql);
		if($result === FALSE) 
		{
			echo mysql_error();
		}
		else 
		{
			
			if($result === 0)
			{
				$amazon_result = execute_query("select product_id from products where aff_uid = '".$uid."'");
				if($row = mysql_fetch_array($amazon_result, MYSQL_ASSOC))
				{
					$product_id = $row['product_id'];
				}
			}
			else
			{
				$product_id = $result;
			}
			echo $product_id, '<br/>';
			if($item_lookup_id != NULL)
			{
				$sql = "INSERT IGNORE INTO amazon_item_lookup_asin (item_lookup_id, aff_uid) values ('$item_lookup_id', '$uid')";
				execute_insert_query($sql);
			}
			
			// Similiar Products
			if(property_exists($item, 'SimilarProducts'))
			{
				
				if(property_exists($item->SimilarProducts, 'SimilarProduct')) 
				{
					
					parseNprocessSimiliarItems($item->SimilarProducts->SimilarProduct, $product_id);
					
				}
			}
		}
	} 
	catch(Exception $e)
	{
		echo json_encode($e),"\r\n<br/>";
	}
}

function parseNprocessSimiliarItems(&$items, $product_id)
{
	global $category_id, $category_name;
	if(is_array($items))
	{
		foreach ($items as $item)
		{
			parseNprocessSimiliarItem($item, $product_id);
		}
	}
	else 
	{
		parseNprocessSimiliarItem($items, $product_id);
	}
}

function parseNprocessSimiliarItem(&$item, $product_id)
{

	
	global $category_id;
	try 
	{	
		$uid = $item->ASIN;
		
		
		$sql = "INSERT IGNORE INTO products_related_temp ( 
				  product_id
				, product_id_related
				, aff_uid_related
				, category_id
			) VALUES ( 
				  $product_id
				, null
				, '$uid'
				, '$category_id'
			)";
		// echo $sql, "\r\n<br/>";
		$result = execute_query ($sql);
		if($result === FALSE) 
		{
			echo mysql_error();
		}
	} 
	catch(Exception $e)
	{
		echo json_encode($e),"\r\n<br/>";
	}	
}
?>